home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 12351 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.2 KB  |  72 lines

  1. Path: itss11.lisd.env.gov.ab.ca!orr
  2. From: orr@lisd.env.gov.ab.ca (Ron Orr)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Output to file vs. cout
  5. Date: 19 Mar 1996 17:05:21 GMT
  6. Organization: Alberta Environmental Protection
  7. Message-ID: <4impgh$jnl@is-news.gov.ab.ca>
  8. References: <JL.96Mar7165152@thyme.id.dth.dk> <4i18mg$ba5@hpbblb.bbn.hp.com>
  9. NNTP-Posting-Host: itss11.lisd.env.gov.ab.ca
  10.  
  11. Matthias Dittrich (matti) wrote:
  12. : jl@id.dth.dk (J°rn Lind-Nielsen) wrote:
  13. : >
  14. : >Here's another of the probs that comes from porting C to C++:
  15. : >
  16. : >- I want to be able to redirect program output to either a file or cout.
  17. : >  Typically this would be selected by a commandline option ("-o outfile").
  18. : >
  19. : >- In C I would do something like this:
  20. : >
  21. : >
  22. : >     main()
  23. : >     {
  24. : >       FILE *outputfile;
  25. : >
  26. : >       if (commandline == do_output_to_file)
  27. : >          outputfile = stdout;
  28. : >       else
  29. : >          outputfile = fopen(passed_filename, "w");
  30. : >
  31. : >       fprintf(outfile, "Hello world\n");
  32. : >
  33. : >       fclose(outfile);  /* Maybe - not allways necassary */
  34. : >     }
  35. : >
  36. : >- The question is:  How is this done in C++ ?
  37. : >
  38. : >.......
  39. : ofstream outfile(passed_filename); /* this constructor opens your file */
  40. : outfile << "Hello world" << endl;  /* writes the string */
  41.  
  42. : The destructor closes the file and of course you should do some error checking.
  43.  
  44. : Good luck,
  45. : Matthias
  46.  
  47. I have the same problem.  This solution will force the output only to
  48. a file.
  49.  
  50. Is there a way to write an output function to do all your output based
  51. on what stream you pass it? ie: one mainline step would be to open a file,
  52. pass the file stream to the function, then close the file.  Another mainline
  53. step would be to pass "cout" to the function.
  54.  
  55. void OutPut(ofstream &xxx)
  56. {
  57.   xxx << "this is only written once"  << endl;
  58. }
  59.  
  60. I tried, but only the file works since it is an oftream object.  "cout" is
  61. an ostream object.
  62.  
  63. Accourding to the g++ FAQ, the iostream classes do not allow assigning to
  64. arbitrary streams, therefore "cout" will fail if passed to this function.
  65.  
  66. So, what is the best way to eliminate duplicate code when you want to
  67. output to a file and/or standard output? I appologize if I have not hunted
  68. through enough FAQS thoroughly and the answer is staring at me.
  69.  
  70. Thanks.  Ron              
  71.  
  72.